package Queue.Queue;

import java.util.Iterator;

public class Queue<T> implements Iterable<T> {

    private class Node<T> {
        T item;
        Node<T> next;

        public Node(T item, Node<T> next) {
            this.item = item;
            this.next = next;
        }
    }

    private Node<T> head;
    private Node<T> last;
    private int N;

    public Queue() {
        this.head = new Node<>(null, null);
        this.last = null;
        N = 0;
    }

    public boolean isEmpty() {
        return N == 0;
    }

    public int size() {
        return N;
    }

    public void enqueue(T t) {
        if (last == null) {
            head.next = last = new Node<>(t, null);
        } else {
            Node<T> node = new Node<>(t, null);
            last.next = node;
            last = node;
        }
        N++;
    }

    public T dequeue() {
        if (isEmpty()) {//safety testing
            return null;
        }
        Node<T> current = head.next;
        head.next = current.next;
        N--;
        if (isEmpty()) {//if queue is empty, we should reset last pointer
            last = null;
        }
        return current.item;
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            private Node<T> current = head;

            @Override
            public boolean hasNext() {
                return current.next != null;
            }

            @Override
            public T next() {
                current = current.next;
                return current.item;
            }
        };
    }
}
